package com.freecloud.whispered.system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.freecloud.framework.exceptions.RRException;
import com.freecloud.framework.service.AbstractBaseService;
import com.freecloud.whispered.system.entity.SysConfigEntity;
import com.freecloud.whispered.system.repository.SysConfigDao;
import com.freecloud.whispered.system.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author maomao
 */
@CacheConfig(cacheNames = {"sysConfigServiceImpl"})
@Service("sysConfigService")
public class SysConfigServiceImpl extends AbstractBaseService<SysConfigEntity,Long, SysConfigDao> implements SysConfigService {

	@Autowired
	private SysConfigDao sysConfigDao;

	@CachePut(key = "targetClass + methodName + #p0")
	@Override
	public void updateValueByKey(String key, String value) {
		sysConfigDao.updateValueByKey(key, value);
	}

	@Cacheable(key = "targetClass + methodName + #p0")
	@Override
	public SysConfigEntity queryObjectByKey(String key){return sysConfigDao.queryObjectByKey(key);}

	@Cacheable(key = "targetClass + methodName + #p0")
	@Override
	public String getValue(String key, String defaultValue) {
		String value = sysConfigDao.queryByKey(key);
		if(StrUtil.isBlank(value)){
			return defaultValue;
		}
		return value;
	}

	@Cacheable(key = "targetClass + methodName + #p0")
	@Override
	public <T> T getConfigObject(String key, Class<T> clazz) {
		String value = getValue(key, null);
		if(StrUtil.isNotBlank(value)){
			return JSONUtil.parseObj(value).toBean(clazz);
		}

		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new RRException("获取参数失败");
		}
	}

	@Cacheable(key = "targetClass + methodName + #p0")
	@Override
	public Long getValueLong(String key, Long defaultValue)
	{
		String longStr = getValue(key,defaultValue != null ? defaultValue.toString () : null);
		if(StrUtil.isBlank(longStr))
		{
			return defaultValue;
		}
		return Long.parseLong (longStr);
	}

}
